#include <stdio.h>

#define TRACE(x...) 
#define PRINT(x...) TRACE(printf(x))

#define rep(i,n) for (int i=0; i<n; i++)

bool vis[3000];
int n, m;
int v, w, p;
int graph[2010][2010];

void DFS(int a) {
	vis[a]=true;

	for (int i=0; i<n; i++) {
		if (!vis[i] && graph[a][i]) DFS(i);
	}
}

int fl=1;

int main() {
	while (1) {
		scanf("%d %d", &n, &m);

		if (!n && !m) break;

		rep(i,n) vis[i]=false;

		rep(i,n) rep(j,n) graph[i][j]=0;

		rep(i,m) {
			scanf("%d %d %d", &v, &w, &p);
			v--; w--;			

			if (p==2) graph[w][v]=1;
			 graph[v][w]=1;	
		}

		TRACE(
			rep(i,n) {
				rep(j,n) printf("%d ", graph[i][j]);
				printf("\n");
			}

			printf("\n");
		)

		DFS(0);
		fl=0;

		rep(i,n) if (!vis[i]) { fl=1; break; }

		if (fl) { printf("0\n"); continue; }

		rep(i,n) 
			for (int j=i+1; j<n; j++) {
				int tmp = graph[i][j];
				graph[i][j]=graph[j][i];
				graph[j][i]=tmp;
			}
	
		TRACE(
			rep(i,n) {
				rep(j,n) printf("%d ", graph[i][j]);
				printf("\n");
			}

			printf("\n");
		)
	
		rep(i,n) vis[i]=false;
		DFS(0);
	
		rep(i,n) if (!vis[i]) { fl=1; break; }
		
		if (fl) printf("0\n");
		else printf("1\n");
	}

	return 0;
}
